import * as Dayjs from 'dayjs'
import React, { useState, useEffect, useMemo } from 'react'
import { observer, inject } from 'mobx-react'
import classNames from 'classnames'
import { omit } from 'lodash'

import video from '../../store/video'
import timeArea from '../../store/time-area'

import '../styles/toolbar/time-area.css'
import useSubs from '../../hooks/useSubs'

const LiveTime = ({ start = null, end = null, event$ }) => {
  const { curScreenId } = video

  const now = new Dayjs()
  const [timeRange, setTimeRange] = useState(resetTime())
  const [isRecord, setIsRecord] = useState(false)

  useSubs(({ action, val }) => {
    // 关闭视频，重置时间
    if (action === 'resetTime') {
      setTimeRange(resetTime())
      timeArea.changeTimeArray(curScreenId, timeRange)
    }
    if (action === 'changeLiveTime') {
      const { id, time } = val
      timeArea.setTimeArray(id, 'now', time.now)
      setTimeRange({ ...omit(time, ['id']) })
    }
  })

  function timeFormat(time) {
    return time ? time.format('MM-DD HH:mm:ss') : ''
  }

  function withinOneDay(start, end) {
    if (start.diff(end, 'hour') > 24) {
      setTimeRange({
        start,
        now: start,
        end: timeFormat(start.add(1, 'day')),
      })
    }
  }

  function legalTime(start, end) {
    if (start != null && end == null) {
      setTimeRange({
        start,
        now: start,
        end: start.add(1, 'day'),
      })
    } else if (start == null && end != null) {
      setTimeRange({
        start: start.subtract(1, 'day'),
        now: start.subtract(1, 'day'),
        end,
      })
    } else if (start == null && end == null) {
      start = timeRange.start
      end = timeRange.end
    }
    withinOneDay(start, end)
  }

  function resetTime() {
    return {
      start: now.subtract(1, 'day'),
      now: now.subtract(1, 'day'),
      end: now,
    }
  }

  useEffect(() => {
    legalTime(start, end)
  }, [start, end])

  // 聚焦分屏，获取分屏对应的时间信息
  useEffect(() => {
    if (curScreenId) {
      const time = timeArea.getTimeById(curScreenId)
      if (time) {
        setTimeRange({ ...omit(time, ['id']) })
      } else {
        const rTime = resetTime()
        setTimeRange({ ...rTime })
        timeArea.addTimeArray(curScreenId, { ...rTime })
      }
    }
  }, [curScreenId])

  useMemo(() => {
    video.videoType === 'live' ? setIsRecord(false) : setIsRecord(true)
  }, [video.videoType])

  return (
    <span className={classNames({ 'time-text': true, 'time-visible': !isRecord, 'time-invisible': isRecord })}>
      {timeFormat(timeRange.now)} / {timeFormat(timeRange.end)}
    </span>
  )
}

export default observer(LiveTime)
